import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/constants/app_contstants.dart';
import 'package:fsharing/core/models/me.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/ui/pages/mine/webview_page.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/login_button.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SettingPage extends StatelessWidget {
  final Me me;

  SettingPage({
    Key key,
    @required this.me,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BackgroundContainer(
      child: Scaffold(
        appBar: AppBar(
          leading: RoundBackButton(),
          title: Text('设置'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              _HeaderWidget(me: me),
              SizedBox(height: 10),
              _ListItemWidget(
                title: '修改密码',
                function: () {
                  Navigator.of(context).pushNamed('/user/password');
                },
              ),
              SizedBox(height: 10),
              Container(
                color: Colors.white,
                child: Column(
                  children: <Widget>[
                    _ListItemWidget(
                      title: '关于我们',
                      function: () {
                        _onAboutClicked(context);
                      },
                    ),
                    _DividerWidget(),
                    _ListItemWidget(
                      title: '用户协议',
                      function: () {
                        _onAgreementClicked(context);
                      },
                    ),
                    _DividerWidget(),
                    _ListItemWidget(
                      title: '清理缓存',
                      function: () {
                        showToast('已清理');
                      },
                    ),
                    _DividerWidget(),
                    _ListItemWidget(
                      title: '更新版本',
                      function: () {
                        showToast('已经是最新版本');
                      },
                    ),
                  ],
                ),
              ),
              SizedBox(height: 45),
              LoginButton(
                title: '退出登录',
                function: () => _logout(context),
              ),
              Container(
                margin: EdgeInsets.all(32),
                child: FutureBuilder(
                  future: _getVersion(),
                  builder: (context, snapshot) {
                    String version = snapshot.hasData ? snapshot.data : '--';
                    return Text(
                      '当前版本 $version',
                      style: TextStyle(fontSize: 18),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _onAgreementClicked(BuildContext context) async {
    AppStoreModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed(
      '/webview',
      arguments: WebViewPageArgs(
        '用户协议',
        '请仔细阅读以下条款：',
        '$api_base_url/app/protocol?sid=${model.bindingStoreId}',
      ),
    );
  }

  void _onAboutClicked(BuildContext context) async {
    AppStoreModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed(
      '/webview',
      arguments: WebViewPageArgs(
        '关于我们',
        '',
        '$api_base_url/app/about?sid=${model.bindingStoreId}',
      ),
    );
  }

  void _logout(BuildContext context) async {
    AppLoginModel appLoginModel = Provider.of(context);
    appLoginModel.isLogin = false;
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.remove('accessToken');
    Navigator.of(context).pop();
  }

  Future<String> _getVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }
}

class _HeaderWidget extends StatelessWidget {
  final Me me;

  const _HeaderWidget({
    Key key,
    @required this.me,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/setting/img_header.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 90,
      child: Row(
        children: <Widget>[
          SizedBox(width: 12),
          CircleAvatar(
            radius: 30,
            backgroundImage: CachedNetworkImageProvider(me.avatar),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  me.nickname ?? '暂无昵称',
                  style: TextStyle(fontSize: 17),
                ),
                SizedBox(height: 8),
                Text(
                  '会员号：${me.username}',
                  style: TextStyle(fontSize: 12),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/setting/img_edit.png'),
                fit: BoxFit.fill,
              ),
            ),
            width: 60,
            height: 30,
            child: Text('编辑'),
          ),
          SizedBox(width: 17)
        ],
      ),
    );
  }
}

class _DividerWidget extends StatelessWidget {
  const _DividerWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Divider(height: 1, indent: 17, color: Colors.black12);
  }
}

class _ListItemWidget extends StatelessWidget {
  final String title;
  final Function function;

  const _ListItemWidget({
    Key key,
    @required this.title,
    @required this.function,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        color: Colors.white,
        height: 45,
        child: Row(
          children: <Widget>[
            SizedBox(width: 17),
            Expanded(
              child: Text(
                title,
                style: TextStyle(color: Color(0xFF333333), fontSize: 16),
              ),
            ),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colors.black26,
            ),
            SizedBox(width: 8),
          ],
        ),
      ),
      onTap: function,
    );
  }
}
